<?php 
class ControllerBlogComment extends Controller {  
	public function write() {
		$this->language->load('blog/comment');
		
		$this->load->model('blog/comment');
		
		$json = array();
		
		if ($this->request->server['REQUEST_METHOD'] == 'POST') {
			
			if (empty($this->session->data['captcha']) || ($this->session->data['captcha'] != $this->request->post['captcha'])) {
				$json['error'] = $this->language->get('error_captcha');
			}

			if ((utf8_strlen($this->request->post['text']) < 25) || (utf8_strlen($this->request->post['text']) > 1000)) {
				$json['error'] = $this->language->get('error_content');
			}

			if ((utf8_strlen($this->request->post['email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['email'])) {
				$json['error'] = $this->language->get('error_email');
			}
			
			if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 25)) {
				$json['error'] = $this->language->get('error_name');
			}
				
			if (!isset($json['error'])) {
				$this->model_blog_comment->addComment($this->request->get['post_id'], $this->request->post);
				
				$json['success'] = $this->language->get('text_success');
			}
		}
		
		$this->response->setOutput(json_encode($json));
	}
	
	
		
	public function index() {
    	$this->language->load('blog/comment');
		
		$this->load->model('blog/comment');

		$this->data['text_no_comments'] = $this->language->get('text_no_comments');

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}  
		
		$this->data['comments'] = array();
		
		$comment_total = $this->model_blog_comment->getTotalCommentsByPostId($this->request->get['post_id']);
			
		$results = $this->model_blog_comment->getCommentsByPostId($this->request->get['post_id'], ($page - 1) * 5, 5);
      		
		foreach ($results as $result) {
        	$this->data['comments'][] = array(
        		'author'     => $result['author_name'],
				'text'       => $result['content'],
        		'date_added' => strtotime($result['created'])
        	);
      	}			
			
		$pagination = new Pagination();
		$pagination->total = $comment_total;
		$pagination->page = $page;
		$pagination->limit = 5; 
		$pagination->text = $this->language->get('text_pagination');
		$pagination->url = $this->url->link('blog/comment', 'post_id=' . $this->request->get['post_id'] . '&page={page}');
			
		$this->data['pagination'] = $pagination->render();
		
		
		$this->data['comment_total'] = $comment_total;
		
		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/blog/comments.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/blog/comments.tpl';
		} else {
			$this->template = 'default/template/blog/comments.tpl';
		}
		
		$this->response->setOutput($this->render());
	}
}
?>